package com.zxmseed.generateanalysis.run;

import com.zxmseed.generateanalysis.bo.GenerateProperties;
import com.zxmseed.generateanalysis.util.ExcelKit;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Component
public class GenerateRun implements ApplicationRunner {

    @Autowired
    private GenerateProperties prop;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        String sourcePath = prop.getSourcePath();

        System.out.println("<<<<<<<<<<<<<<<<<<<<<程序开始>>>>>>>>>>>>>>>>>>>");

        // 检查源文件
        File sourceFile = new File(sourcePath);
        if (!sourceFile.exists()) {
            throw new Exception("源文件目录不存在，请检查");
        }

        // 检查源文件夹下文件是否存在
        File[] files = sourceFile.listFiles();
        if (files == null || files.length != 2) {
            throw new Exception("源文件目录下文件不正确，请检查");
        }

        // 检查是否是 txt后缀和 xls或者xlsx
        File execelFile = null;
        File txtFile = null;
        for (File file : files) {
            String fileName = file.getName();
            if (fileName.endsWith("txt") || fileName.endsWith("xls") || fileName.endsWith("xlsx")) {
                System.out.println("扫描到文件：" + file.getName());
                if (fileName.endsWith("txt")) {
                    txtFile = file;
                } else {
                    execelFile = file;
                }
            } else {
                throw new Exception("源文件目录下文件不正确，请检查");
            }
        }

        if (execelFile == null || txtFile == null) {
            throw new Exception("程序崩溃，请技术检查");
        }

        int index = execelFile.getName().lastIndexOf(".");
        String suffix = execelFile.getName().substring(index + 1);

        Map<String, List<List<String>>> excelMap = null;
        try {
            Workbook workbook = ExcelKit.getWorkbook(new FileInputStream(execelFile), suffix);
            excelMap = ExcelKit.parseExcel(workbook);
        } catch (IOException e) {
            throw new Exception("关键词Excel读内容错误，请检查", e);
        }

        List<List<String>> keysList = excelMap.get("sheet1");
        if (keysList == null || keysList.size() == 0) {
            throw new Exception("关键词Excel未读取到内容，请检查");
        }

        List<String> keys = keysList.stream()
                .filter(row -> row != null && StringUtils.isNotBlank(row.get(0))
                        && !Objects.equals("关键词", row.get(0).trim()))
                .map(row -> row.get(0).trim())
                .collect(Collectors.toList());

        // 创建生成目录
        System.out.println("删除生成目录");
        FileUtils.deleteDirectory(new File(prop.getTargetPath()));
        System.out.println("创建生成目录");
        FileUtils.forceMkdir(new File(prop.getTargetPath()));

        List<String> lines = FileUtils.readLines(txtFile, prop.getCode());
        StringBuilder builder = new StringBuilder();
        for (String line : lines) {
            if (StringUtils.isNotBlank(line)) {
                String newStr = line.replace("<P>", "#")
                        .replace("</P>", "@");
                builder.append(line.trim());
            }
        }

        List<String> listStr = getListStr(builder.toString());
        if (listStr.size() > keys.size()) {
            throw new Exception("需生成文件为: " + listStr.size() + "个，标题数为：" + keys.size() + "，请检查");
        }

        System.out.println("标题数目：" + keys.size());
        System.out.println("等待生成文件数目：" + listStr.size());

        for (int i = 0; i < listStr.size(); i++) {
            String key = keys.get(i);
            String fileName = key + ".txt";

            int keyNum = RandomUtils.nextInt(prop.getKeyMin(), prop.getKeyMax());
            String source = listStr.get(i).trim();
            int sourceLen = source.length();
            StringBuilder row = new StringBuilder();
            row.append(source);
            for (int k = 1; k <= keyNum; k++) {
                if (k == 1) {
                    row.insert(0, key);
                } else {
                    row.insert(RandomUtils.nextInt(1, sourceLen), key);
                }
            }

            String str = row.toString()
                    .replace("#", "<P>")
                    .replace("@", "</P>");

            if (!str.startsWith("<P>"))
                row.insert(0, "<P>　　");

            if (!str.endsWith("</P>"))
                row.append("</P>");

            System.out.println("生成第[" + i + "]篇文章：" + fileName + "，字数：" + row.length() + "，关键词插入：" + keyNum + " 次");
            FileUtils.writeStringToFile(new File(prop.getTargetPath() + "/" + fileName),
                    row.toString().replace("<</P>", "")
                            .replace("<P>>", ""), "UTF-8");
        }

        System.out.println("<<<<<<<<<<<<<<<<<<<<<程序结束>>>>>>>>>>>>>>>>>>>");
        Runtime.getRuntime().exec("cmd /c start " + prop.getTargetPath());
    }

    public List<String> getListStr(String str) {
        List<String> listStr = new ArrayList<>();
        int strLen = str.length();
        int end = 0;
        int start = 0;
        String temp = null;
        while (true) {
            int num = RandomUtils.nextInt(prop.getMin(), prop.getMax());
            end += num;
            try {
                if (end >= strLen) {
                    temp = str.substring(start, strLen);
                } else {
                    temp = str.substring(start, end);
                }
            } catch (Exception e) {
                break;
            }
            listStr.add(temp);
            start += num;
        }
        return listStr;
    }
}
